namespace study44 {
  /**
   * instanceof 
   * 1. 检测一个对象是否是某个类或其子类的实例
   * 2. instanceof 检测的是对象的原型链，因此可以判断出对象是否是某个构造函数创建的实例。
   */

  // 1. 基本用法
  class Animal {
    constructor(public name: string) { }
  }

  class Dog extends Animal {
    constructor(name: string, public breed: string) { super(name); }
  }

  let myDog = new Dog("Buddy", "Golden Retriever");

  console.log(myDog instanceof Dog); // true
  console.log(myDog instanceof Animal); // true
  console.log(myDog instanceof Object); // true

  // 2. instanceof 与类型保护（尽量不要使用类型断言）
  class Bird {
    fly() {
      console.log("Flying...");
    }
  }

  class Fish {
    swim() {
      console.log("Swimming...");
    }
  }

  function move(animal: Bird | Fish) {
    if (animal instanceof Bird) {
      animal.fly();
    } else if (animal instanceof Fish) {
      animal.swim();
    } else {
      console.log("Not a Bird or a Fish");
    }
  }

  // 3. instanceof 与自定义类
  interface Car {
    drive(): void;
  }

  class Sedan implements Car {
    drive() {
      console.log("Driving a sedan...");
    }
  }

  let myCar: Car = new Sedan();
  console.log(myCar instanceof Sedan); // true
  // console.log(myCar instanceof Car); // false，Car是接口，不是类
  console.log(myCar instanceof Object); // true

  // 4. instanceof 与内置类型
  let arr = [1, 2, 3];
  let date = new Date();
  let error = new Error("Something went wrong");

  console.log(arr instanceof Array); // true
  console.log(date instanceof Date); // true
  console.log(error instanceof Error); // true

}